package com.example.mall.service;

import com.example.mall.common.core.exception.ParameterException;
import com.example.mall.common.utils.JwtToken;
import com.example.mall.dto.token.TokenGetDTO;
import com.example.mall.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信-登录认证
 */
@Service
public class WxAuthenticationService {
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Value("${wx.wxurl}")
    private String wxurl;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private UserService userService;

    /**
     * 根据小程序客户端发送的code -> 去 微信 上换取用户的openid
     * @param code
     */
    public String code2Session(String code) {
        String url = MessageFormat.format(wxurl, appid, secret, code);
        RestTemplate reqeust = new RestTemplate();
        // 请求
        String sessionText = reqeust.getForObject(url, String.class);
        Map<String, Object> session = new HashMap<>();
        try {
            session = objectMapper.readValue(sessionText, Map.class);
        } catch (JsonProcessingException e) {
            // 根据微信api错误状态码处理异常
            e.printStackTrace();
        }
        return registerToken(session);
    }

    /**
     * 注册微信新用户并生成令牌
     * @return
     */
    private String registerToken(Map<String, Object> session) {
        // 查询数据库比对 openid,没记录 则为新用户,新建用户
        String openid = (String)session.get("openid");
        if (openid == null) {
            // 日志 TODO
            throw new ParameterException(20004);
        }

        // 查表
        User user = userService.selectOneByUsername(openid);
        if (user == null) {
            // 新用户,保存入库
            userService.save(User.builder().username(openid).build());
            // 如何实现写入
            user = userService.selectOneByUsername(openid);
        }
        // 生成token令牌
        return JwtToken.generalToken(user.getId());
    }

    public void valify(TokenGetDTO tokenGetDTO) {

    }


}
